package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.FamilyBindResponseVO;
import com.zzyl.nursing.vo.FamilyListVo;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 * 
 * @author laoYe
 * @date 2025-10-27
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired// 要使用若依框架
    private TokenService tokenService;

    @Autowired
    private ElderMapper elderMapper;

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    private static List<String> DEFAULT_NICKNAME_PREFIX = List.of(
        "生活更美好",
        "大桔大利",
        "日富一日",
        "好柿开花",
        "柿柿如意",
        "一椰暴富",
        "大柚所为",
        "杨梅吐气",
        "天生荔枝"
    );

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        // 创建一个vo
        LoginVo vo = new LoginVo();
        //1. 获取openId
        String openId = wechatService.getOpenId(dto.getCode());
        //2. 获取用户的手机号码
        String phone = wechatService.getPhoneNumber(dto.getPhoneCode());
        //3. 通过openId查询用户信息
        FamilyMember memberInDB = lambdaQuery().eq(FamilyMember::getOpenId, openId).one();
        // 创建一个保存的实体类
        FamilyMember newFamilyMember = new FamilyMember();
        // 设置要保存的手机号码
        newFamilyMember.setPhone(phone);
        //4. 判断用户是否存在
        if(memberInDB != null) {
            vo.setNickName(memberInDB.getName());
            // 更新条件为主键id
            newFamilyMember.setId(memberInDB.getId());
            //5. 存在
            // 手机号码是否有变更，有变更则要更新
            if(!memberInDB.getPhone().equals(phone)) {
                //update 表名 set 字段名 = 值 where id = ?, 明确更新的字段
                updateById(newFamilyMember);
            }
        }else {
            //6. 不存在,新增
            newFamilyMember.setOpenId(openId);
            // 昵称
            // 随机组装昵称，词组+手机号后四位
            String nickName = generateNickname(phone);
            newFamilyMember.setName(nickName);
            save(newFamilyMember);
            vo.setNickName(nickName);
        }
        //7. 把用户id与nickname封装到token返回
        Map<String,Object> claims = new HashMap<String,Object>();
        claims.put("userId", newFamilyMember.getId());
        claims.put("nickName", vo.getNickName());
        String token = tokenService.createToken(claims);
        vo.setToken(token);
        return vo;
    }


    /**
     *
     * 绑定老人
     * @param dto
     * @return
     */
    @Override
    public void addFamily(FamilyMemberElder dto) {
        // 1. 根据身份证查老人
        Elder elder = elderMapper.selectOne(
                new LambdaQueryWrapper<Elder>()
                        .eq(Elder::getIdCardNo, dto.getIdCard())
                        .eq(Elder::getName, dto.getName())
        );
        if (elder == null) {
            throw new RuntimeException("该老人不存在");
        }

        // 2. 获取当前登录的家属ID (关键修复)

        Long familyMemberId = UserThreadLocal.getUserId();
        if (familyMemberId == null) {throw new RuntimeException("用户未登录");}

        // 3. 创建并保存关联记录
        FamilyMemberElder record = new FamilyMemberElder();
        record.setFamilyMemberId(familyMemberId); // 正确设置
        record.setCreateBy(familyMemberId);
        record.setUpdateBy(familyMemberId);
        record.setElderId(elder.getId());
        record.setRemark(dto.getRemark());
        record.setCreateTime(LocalDateTime.now());
        record.setUpdateTime(LocalDateTime.now());

        familyMemberMapper.insertFamilyMemberElder(record);
    }

    /**
     * 获取家人
     * @return
     */
    @Override
    public List<FamilyBindResponseVO> getMyFamilies() {
        Long familyMemberId = UserThreadLocal.getUserId();
        if (familyMemberId == null){ return Collections.emptyList();}

        // 需要在 FamilyMemberMapper 中添加此方法来查询数据库
        return familyMemberMapper.selectBindListByFamilyMemberId(familyMemberId);
    }

    /**
     * 分页查询家属列表
     */
    @Override
    public List<FamilyListVo> listByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<FamilyListVo> list = familyMemberMapper.listElderByPageByMemberId(UserThreadLocal.getUserId());
        return list;
    }
    /**
     * 生成随机昵称
     * @param phone
     * @return
     */
    private String generateNickname(String phone) {
        Random r = new Random();
        int prefixIndex = r.nextInt(DEFAULT_NICKNAME_PREFIX.size());
        String prefix = DEFAULT_NICKNAME_PREFIX.get(prefixIndex);
        // 手机号后四位
        String suffix = phone.substring(phone.length() - 4);
        return prefix + suffix;
    }


}
